<template>
  <div class="enterpriseDialog">
    <el-dialog
      v-dialogDrag
      :title="title"
      :visible.sync="dialogVisible"
      :width="width"
      :before-close="handelClose"
      :close-on-click-modal="false"
      append-to-body
    >
      <div class="enterpriseDialog_center">
        <div v-if="isDisable" class="tips">系统检测到您正在修改预算云的数据,项目名称无法修改</div>
        <div>
          <el-form ref="createForm" style="width:95%;margin-left:2.5%" :model="createForm" :rules="rulesForm" label-width="120px">
            <el-form-item label="项目名称" prop="name">
              <el-input v-model="createForm.name" :disabled="isDisable" />
            </el-form-item>
            <!-- prop="financialMatters" -->
            <el-form-item label="集中财力办大事">
              <el-select v-model="filterList[0].value" style="width:100%" filterable clearable :placeholder="filterList[0].placeholder" @change="changeSelect">
                <el-option
                  v-for="(item1,index1) in selectOption"
                  :key="index1"
                  :label="item1[filterList[0].showLabel]"
                  :value="item1[filterList[0].showValue]"
                />
              </el-select>
              <!-- <selectTree :param-type="'0002'" :common-index="0" :show-label="filterList[0].showLabel" :item-url="filterList[0].url" :placeholder="filterList[0].placeholder" :common-values="filterList[0].value" @changeData="changeData" /> -->
            </el-form-item>
            <!-- prop="livelihood" -->
            <el-form-item label="是否民生支出">
              <el-radio-group v-model="createForm.livelihood">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <div class="table">
            <vxe-table
              :align="allAlign"
              :data="tableData"
              border
            >
              <vxe-table-colgroup title="控制额">
                <vxe-table-column field="allYear" title="全年平衡(元)" />
                <vxe-table-column field="initialBudget" title="年初预算(元)">
                  <!--  @focus="focusInput(scope.row)"
                      @input="handleClick(scope.row)" -->
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.initialBudget"
                      clearable
                      @input="handleClick(scope.row,'initialBudget')"
                    />
                  </template>
                </vxe-table-column>
                <vxe-table-column field="beginBudget" title="年初确定控制额(元)">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.beginBudget"
                      clearable
                      @input="handleClick(scope.row,'beginBudget')"
                    />
                  </template>
                </vxe-table-column>
                <vxe-table-column field="middleBudget" title="年中增加控制额(元)">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.middleBudget"
                      clearable
                      @input="handleClick(scope.row,'middleBudget')"
                    />
                  </template>
                </vxe-table-column>
              </vxe-table-colgroup>
            </vxe-table>
          </div>
          <div class="table">
            <vxe-table
              :align="allAlign"
              :data="tableData1"
              border
            >
              <vxe-table-colgroup title="指标已落实金额">
                <vxe-table-column field="allMoney" title="合计(元)" />
                <vxe-table-column field="workableFc" title="指标分口余额(元)">
                  <!--  @focus="focusInput(scope.row)"
                      @input="handleClick(scope.row)" -->
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.workableFc"

                      clearable
                      @input="handleClick(scope.row,'workableFc')"
                    />
                  </template>
                </vxe-table-column>
                <vxe-table-column field="workablePlan" title="用款计划预算数(元)">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.workablePlan"

                      clearable
                      @input="handleClick(scope.row,'workablePlan')"
                    />
                  </template>
                </vxe-table-column>
                <vxe-table-column field="workableAdd" title="追加审批数(元)">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.workableAdd"
                      clearable
                      @input="handleClick(scope.row,'workableAdd')"
                    />
                  </template>
                </vxe-table-column>
              </vxe-table-colgroup>
            </vxe-table>
          </div>
          <div class="enterpriseDialog_center_edit">
            <div class="enterpriseDialog_center_edit_title">计算依据:</div>
            <div>
              <el-input v-model="createForm.basis" type="textarea" :rows="5" placeholder="请输入计算依据" />
            </div>
          </div>

        </div>

      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handelClose">取 消</el-button>
        <el-button v-if="title===&quot;新增项目&quot;" :loading="isSubmit" type="primary" @click="submitForm">新 增</el-button>
        <el-button v-if="title===&quot;修改项目&quot;" :loading="isSubmit1" type="primary" @click="submitForm">修 改</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getProgramList, doFormMethod } from '@/api/projectLibrary/index';
import { Message } from 'element-ui';
// import selectTree from '@/components/SelectTree/index.vue';

export default {
  components: {
    // selectTree
  },
  data() {
    return {
      allAlign: 'center',
      isDisable: false,
      // selectOption: [],
      tableData: [{
        allYear: '',
        initialBudget: '',
        beginBudget: '',
        middleBudget: ''
      }],
      tableData1: [{
        allMoney: '',
        workableFc: '',
        workablePlan: '',
        workableAdd: ''
      }],

      title: '项目基本信息',
      dialogVisible: false,
      width: '50%',
      programGuid: '',
      isSubmit: false,
      isSubmit1: false,
      createForm: {
        name: '',
        year: localStorage.getItem('chooseYear'),
        livelihood: '',
        financialMatters: '',
        basis: ''
      },
      // 存放选择的条件
      filterList: [
        // 0 是下拉树 1 是input 2 是下拉框
        {
          // 集中财力办大事
          url: 'option/findByType',
          placeholder: '集中财力办大事',
          formType: '2',
          value: '',
          symbol: 'eq',
          showLabel: 'name',
          showValue: 'name',
          col: 'FINANCIALMATTERS'
        }

      ],
      rulesForm: {
        name: [
          { required: true, message: '项目名称不能为空' }
        ]
        // livelihood: [
        //   { required: true, message: '民生支出不能为空' }
        // ],
        // financialMatters: [
        //   { required: true, message: '集中财力办大事不能为空' }
        // ]

      }

    };
  },
  computed: {
    selectOption() {
      const obj = this.$store.state.adminOption.optionList.find(i => i.code === '0002');
      return obj && obj.children;
    }
  },
  created() {
    // 获取系统内置
    this.$store.dispatch('adminOption/getListOptions');
  },
  methods: {
    // getSelectFouce(url, placeholder) {
    //   getCommonDataSource({
    //     type: '0002',
    //     resultAsTree: true
    //   }, url).then(res => {
    //     if (res.success) {
    //       this.selectOption = res.data;
    //     } else {
    //       this.selectOption = [];
    //     }
    //   });
    // },
    handleClick(row, type) {
      // row[type] = ('' + row[type]) // 第一步：转成字符串
      //   .replace(/[^\d^\.]+/g, '') // 第二步：把不是数字，不是小数点的过滤掉
      //   .replace(/^0+(\d)/, '$1') // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
      //   .replace(/^\./, '0.') // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
      //   .match(/^\d*(\.?\d{0,2})/g)[0] || ''; // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数
      this.tableData[0].allYear = (Number(this.tableData[0].initialBudget) + Number(this.tableData[0].beginBudget) +
       Number(this.tableData[0].middleBudget)).toFixed(2);

      this.tableData1[0].allMoney = (Number(this.tableData1[0].workableFc) + Number(this.tableData1[0].workablePlan) +
       Number(this.tableData1[0].workableAdd)).toFixed(2);
    },
    changeSelect() {
      this.createForm.financialMatters = this.filterList[0].value;
    },
    handelClose() {
      this.dialogVisible = false;
      this.programGuid = '';
      this.createForm = {
        name: '',
        year: localStorage.getItem('chooseYear'),
        livelihood: '',
        financialMatters: '',
        basis: ''
      };
      this.tableData = [{
        allYear: '',
        initialBudget: '',
        beginBudget: '',
        middleBudget: ''
      }];
      this.tableData1 = [{
        allMoney: '',
        workableFc: '',
        workablePlan: '',
        workableAdd: ''
      }];
      this.filterList = [
        // 0 是下拉树 1 是input 2 是下拉框
        {
          // 集中财力办大事
          url: 'option/findByType',
          placeholder: '集中财力办大事',
          formType: '2',
          value: '',
          symbol: 'eq',
          showLabel: 'text',
          showValue: 'id',
          col: 'FINANCIALMATTERS'
        }
      ];
    },
    isvagueForm() {
      // else if (this.createForm.livelihood === '') {
      //   Message({
      //     message: '民生支出不能为空',
      //     type: 'warning'
      //   });
      // } else if (this.createForm.financialMatters === '') {
      //   Message({
      //     message: '集中财力办大事不能为空',
      //     type: 'warning'
      //   });
      // }

      if (this.createForm.name === '') {
        Message({
          message: '项目名称不能为空',
          type: 'warning'
        });
      } else {
        // 模糊查询
        getProgramList({
          year: localStorage.getItem('chooseYear'),
          status: 1,
          nameLike: this.createForm.name
        }).then(res => {
          if (res.success) {
            if (res.data.length === 0) {
              // 直接创建
              this.commonForm();
            } else {
              // 给提示, 在创建
              let tips = `<div style='font-size:15px;font-weight:bolder'>请注意!项目名称<span style='color:red'>${this.createForm.name}</span>在预算云中有类似的项目:</div>`;
              for (let i = 0; i < res.data.length; i++) {
                tips += `<div style='margin-top:10px'>${res.data[i].name}</div>`;
              }
              this.$confirm(tips, '提示', {
                dangerouslyUseHTMLString: true,
                confirmButtonText: '继续提交',
                cancelButtonText: '返回修改',
                type: 'warning'
              }).then(() => {
                this.commonForm();
              }).catch(() => {

              });
            }
          }
        });
      }
    },
    commonForm() {
      let url = '';
      let successMessage = '';
      // let failMessage = '';
      if (this.title === '新增项目') {
        url = 'project/insProject';
        successMessage = '添加项目成功';
        // failMessage = '添加项目失败';
        this.isSubmit = true;
      } else {
        url = 'project/editBudget';
        this.isSubmit1 = true;
        successMessage = '修改项目成功';
        // failMessage = '修改项目失败';
      }
      doFormMethod(url, {
        ...this.createForm,
        ...this.tableData[0],
        ...this.tableData1[0],
        enterpriseGuid: this.$parent.$refs.enterpriseTree.enterpriseGuid,
        programGuid: this.programGuid
      }).then(res => {
        this.isSubmit1 = false;
        this.isSubmit = false;
        if (res.success) {
          Message({
            message: successMessage,
            type: 'success'
          });
          this.$parent.getData();
          this.handelClose();
        } else {
          Message({
            message: res.message,
            type: 'warning'
          });
        }
      });
    },
    submitForm() {
      if (this.title === '新增项目') {
        this.isvagueForm();
      } else {
        // else if (this.createForm.livelihood === '') {
        //   Message({
        //     message: '民生支出不能为空',
        //     type: 'warning'
        //   });
        // } else if (this.createForm.financialMatters === '') {
        //   Message({
        //     message: '集中财力办大事不能为空',
        //     type: 'warning'
        //   });
        // }
        if (this.createForm.name === '') {
          Message({
            message: '项目名称不能为空',
            type: 'warning'
          });
        } else {
          this.commonForm();
        }
      }
    }
  }
};
</script>
<style lang='scss' scoped>
.roleClass {
  border: 1px solid #dcdfe6;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
  cursor: pointer;
  border-radius: 5px;
  text-align: center;
  margin: 5px;
}

.activeRoleClass {
  border: 1px solid #39bd65;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
  cursor: pointer;
  border-radius: 5px;
  text-align: center;
  margin: 5px;
}
.enterpriseDialog_record {
  margin-top: 10px;
  border-top: 1px solid #c5bcbc;
  height: 200px;
  overflow-y: auto;
}
.enterpriseDialog_record_title {
  color: red;
  margin-top: 10px;
  margin-bottom: 10px;
}
.enterpriseDialog ::v-deep .el-dialog {
  margin-top: 5vh !important;
  width: 60% !important;
}
.enterpriseDialog_center_edit_title{
  margin-bottom: 10px
}
.table{
  margin-bottom: 15px;
  margin-top: 20px
}
.tips{
  color: red;
  font-size: 13px;
  margin-bottom: 10px
}
</style>
